package com.gary.security.action;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONException;

import org.apache.struts2.ServletActionContext;

import com.gary.core.action.BaseAction;
import com.gary.core.orm.query.QueryFilter;
import com.gary.core.orm.utils.PageList;
import com.gary.core.util.BeanUtil;
import com.gary.core.util.JsonUtils;
import com.gary.security.model.RescInfo;
import com.gary.security.repository.RescRepository;


/**
 * resc action.
 *
 */
public class RescAction extends BaseAction<RescInfo> {
    /** * serial. */
    static final long serialVersionUID = 0L;

    /** * resc manager. */
    private transient RescRepository rescReps = null;

    /** * resc list. */
    private List<RescInfo> list;

    /** * id. */
    private long id;

    // ====================================================
    private int start;
    private int limit;
    private String sort;
    private String dir;
    private String ids;

    /** * @return success. */
    public String list() {
        this.list = rescReps.getAll();

        return SUCCESS;
    }

    /** * @return forward. */
    public String edit() {
        this.model = rescReps.getById(id,true);

        return "forward";
    }
    //
    /** * @param rescManager resc manager. */
    public void setRescReps(RescRepository rescReps) {
        this.rescReps = rescReps;
    }

    /** * @return resc list. */
    public List<RescInfo> getList() {
        return list;
    }

    /** * @param id long. */
    public void setId(long id) {
        this.id = id;
    }

    // ====================================================
    public void setStart(int start) {
        this.start = start;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    public void setDir(String dir) {
        this.dir = dir;
    }


    /**
     * 分页浏览记录.
     *
     * @throws Exception 异常
     */
    public void pagedQuery() throws Exception {
        // 分页
        int pageNo = (start / limit) + 1;
        
        QueryFilter filter = new QueryFilter();

        if (sort != null) {
            filter.addOrderBy(sort,dir);
        }

        PageList page = rescReps.getPageList(filter, pageNo, limit);

        JsonUtils.write(page,
            ServletActionContext.getResponse().getWriter(), getExcludes(),
            getDatePattern());
    }

    /**
     * 使用json绑定pojo，再将绑定的pojo返回.
     *
     * @return T entity
     * @throws Exception 解析时，可能抛出异常
     */
    protected RescInfo bindObject() throws Exception {
        RescInfo resc = null;

        try {
            resc = rescReps.getById(model.getId(),false);
        } catch (JSONException ex) {
            System.err.println(ex);
        }

        if (resc == null) {
            resc = model;
        } else {
            BeanUtil.copyProperties(model, resc);
        }

        if ("METHOD".equals(resc.getResType())) {
            String resString = resc.getResString();

            try {
                int lastDotIndex = resString.lastIndexOf('.');
                String className = resString.substring(0, lastDotIndex);
                //String methodName = resString.substring(lastDotIndex + 1);

                //Class rescClass = Class.forName(className);
                Class.forName(className);
            } catch (Exception ex) {
                System.err.println("resString内容不正确：" + ex.toString());
                throw ex;
            }
        }

        return resc;
    }

    /**
     * 保存，新增或修改.
     *
     * @throws Exception 异常
     */
    public void save() throws Exception {
        RescInfo entity = bindObject();

        rescReps.save(entity);
        ServletActionContext.getResponse().getWriter()
                            .print("{success:true}");
    }

    /**
     * 读取数据.
     *
     * @throws Exception 异常
     */
    public void loadData() throws Exception {
        RescInfo entity = rescReps.getById(id,false);

        if (entity != null) {
            List<RescInfo> list = new ArrayList<RescInfo>();
            list.add(entity);
            JsonUtils.write(list,
                ServletActionContext.getResponse().getWriter(),
                getExcludes(), getDatePattern());
        }
    }

    /**
     * 删除记录.
     *
     * @throws Exception 异常
     */
    public void remove() throws Exception {
        for (String str : ids.split(",")) {
            try {
                long id = Long.parseLong(str);
                rescReps.deleteById(id);
            } catch (NumberFormatException ex) {
                continue;
            }
        }

        ServletActionContext.getResponse().getWriter()
                            .print("{success:true}");
    }

    public void setIds(String ids) {
        this.ids = ids;
    }


    /** * @return excludes. */
    public String[] getExcludes() {
        return new String[] {"roles", "rescs", "users"};
    }

    public String getDatePattern() {
        return "yyyy-MM-dd";
    }
}
